package net.xdclass.interceptor;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.exception.BizException;
import net.xdclass.model.LoginUser;
import net.xdclass.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 用户登录拦截器
 *
 * @author JiangZhou
 * @date 2023/5/3 14:01
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String accessToken = request.getHeader("token");
        if (accessToken == null) {
            accessToken = request.getParameter("token");
        }
        if (StringUtils.isNotBlank(accessToken)) {
            //如果token不为空
            Claims claims = JWTUtil.checkJwt(accessToken);
            if (claims == null) {
                throw new BizException(BizCodeEnum.USER_NOT_LOGIN);
            }
            //获取用户信息
            long id = Long.parseLong(claims.get("id").toString());
            String headImg = (String) claims.get("head_img");
            String name = claims.get("name").toString();
            String mail = claims.get("mail").toString();

            LoginUser loginUser = new LoginUser();
            loginUser.setId(id);
            loginUser.setMail(mail);
            loginUser.setHead_img(headImg);
            loginUser.setName(name);
            threadLocal.set(loginUser);
            return true;
        }

        throw new BizException(BizCodeEnum.USER_NOT_LOGIN);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
